package com.tiantian.web.controller.user;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.tiantian.bean.PageBean;
import com.tiantian.cache.RegionalInformationCache;
import com.tiantian.dao.BusinessStoreRepository;
import com.tiantian.domain.Bindingplatformaccounts;
import com.tiantian.domain.Businessstore;
import com.tiantian.domain.Businessusers;
import com.tiantian.domain.Buyersbankcard;
import com.tiantian.domain.BuyersbankcardId;
import com.tiantian.domain.Buyersusers;
import com.tiantian.poi.PoiReportBuilder;
import com.tiantian.ret.Result;
import com.tiantian.service.BindingPlatformAccountsService;
import com.tiantian.service.BusinessStoreService;
import com.tiantian.service.BusinessUsersService;
import com.tiantian.service.BuyersBankCardService;
import com.tiantian.service.BuyersUsersService;
import com.tiantian.util.CommonConstant;
import com.tiantian.util.MD5UtilBusyness;
import com.tiantian.util.MD5UtilBuyer;
import com.tiantian.util.PageUtil;
import com.tiantian.web.datatables.DataTableReturn;

/**
 * 用户管理
 * 
 */
@Controller
@RequestMapping("/user")
public class UsersController {
	public static final Logger LOG = LoggerFactory.getLogger(UsersController.class);
	@Resource
	private BusinessUsersService businessUsersService;
	@Resource
	private BuyersUsersService buyersUsersService;
	@Autowired
	private BusinessStoreRepository businessStoreRepository;
	@Autowired
	private RegionalInformationCache regionalInformationCache;
	@Autowired
	private BusinessStoreService businessStoreService;
	@Autowired
	private BuyersBankCardService buyerBankCardService;
	@Autowired
	private BindingPlatformAccountsService bindingPlatformAccountsService;

	/**
	 * 商户列表
	 * 
	 * @param tipBuyersNotes
	 * @return
	 */
	@RequestMapping(value = { "/businessUsersList" })
	public void businessUsersList() {

	}

	/**
	 * 获取商家用户列表
	 * 
	 * @param businessVo
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "/getBusinessUsersList" })
	public Object getBusinessUsersList(BusinessVo businessVo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(businessVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Businessusers> data = businessUsersService.list(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	@RequestMapping(value = { "/reportBusiness" })
	public ModelAndView reportBusiness(BusinessVo businessVo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(businessVo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			List<Businessusers> datas = businessUsersService.getReportlist(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("生财ID", "登陆账号", "注册时间", "联系电话", "QQ", "微信", "账户状态");
			if (datas != null) {
				for (Businessusers data : datas) {
					List<String> poiData = new ArrayList<>();
					poiData.add(data.getBusinessUserId());
					poiData.add(data.getUserName());
					poiData.add(DateFormatUtils.format(data.getRegistrationTime(), CommonConstant.TIME_FORMAT_YMDHMS));
					poiData.add(data.getPhone());
					poiData.add(data.getQqno());
					poiData.add(data.getWechatNo());
					poiData.add(data.getAccountStatus() == 0 ? "使用中" : "已冻结");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "商家账户_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出商家账户异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}

	@RequestMapping(value = { "/businessUserDetail" })
	public void businessUserDetail(@RequestParam String id, Model model) {
		// 商家账户信息
		Businessusers businessusers = businessUsersService.get(id);
		model.addAttribute("user", businessusers);

		// 商家店铺信息
		List<Businessstore> businessstores = businessStoreRepository.findByBusinessUserId(businessusers.getBusinessUserId());
		model.addAttribute("stores", businessstores);
		List<String> addresses = new ArrayList<String>();
		for (Businessstore businessstore : businessstores) {
			String address = "";
			String a1 = regionalInformationCache.getAreaName(businessstore.getShipProvince());
			if (StringUtils.isNotBlank(a1)) {
				address += a1;
			}
			String a2 = regionalInformationCache.getAreaName(businessstore.getShipCities());
			if (StringUtils.isNotBlank(a2)) {
				address += a2;
			}
			String a3 = regionalInformationCache.getAreaName(businessstore.getShipArea());
			if (StringUtils.isNotBlank(a3)) {
				address += a3;
			}
			address += businessstore.getStreetAddress();
			addresses.add(address);
		}
		model.addAttribute("addresses", addresses);
	}

	/**
	 * 商户账号解冻/冻结
	 */
	@RequestMapping(value = { "/editStatus" })
	@ResponseBody
	public Result<?> editStatus(@RequestParam String id, @RequestParam String accountStatus) {

		try {
			Businessusers businessusers = businessUsersService.get(id);
			if ("1".equals(accountStatus.trim())) {
				businessusers.setAccountStatus(0);
				businessUsersService.save(businessusers);
				return new Result<Object>(true, "解冻账户成功");
			} else {
				businessusers.setAccountStatus(1);
				businessUsersService.save(businessusers);
				return new Result<Object>(true, "冻结账户成功");
			}

		} catch (Exception e) {
			LOG.error("更改用户状态异常");
			return new Result<Object>(false, "操作失败");
		}
	}

	@RequestMapping(value = { "/updateBussinessUser" })
	@ResponseBody
	public Result<?> updateBussinessUser(BusinessVo businessVo) {

		try {
			Businessusers businessusers = businessUsersService.get(businessVo.getBusinessUserId());
			if (businessusers != null) {
				businessusers.setUserName(businessVo.getUserName());
				if (!StringUtils.equals("notchange", businessVo.getLoginPassword())) {
					businessusers.setLoginPassword(MD5UtilBusyness.string2MD5(businessVo.getLoginPassword()));
				}
				businessusers.setPhone(businessVo.getPhone());
				businessusers.setQqno(businessVo.getQqno());
				businessusers.setWechatNo(businessVo.getWechatNo());
				businessUsersService.save(businessusers);
				return new Result<Object>(true, "用户信息更新成功");
			} else {
				return new Result<Object>(false, "查找的用户不存在,id:" + businessVo.getBusinessUserId());
			}
		} catch (Exception e) {
			LOG.error("更新用户异常", e);
			return new Result<Object>(false, "操作失败");
		}
	}

	/**
	 * 商户账号解冻/冻结
	 */
	@RequestMapping(value = { "/editStoreStatus" })
	@ResponseBody
	public Result<?> editStoreStatus(@RequestParam String id, @RequestParam String status) {
		try {
			Businessstore businessstore = businessStoreService.get(id);
			if ("1".equals(status.trim())) {// 待审核变为绑定
				businessstore.setBindingStatus('2');
				businessStoreService.save(businessstore);
				return new Result<Object>(true, "绑定商铺成功");
			} else {
				businessstore.setBindingStatus('1');
				businessStoreService.save(businessstore);
				return new Result<Object>(true, "解绑商铺成功");
			}

		} catch (Exception e) {
			LOG.error("更改商铺绑定异常", e);
			return new Result<Object>(false, "操作失败");
		}
	}

	/**
	 * 买手用户列表
	 * 
	 * @param tipBuyersNotes
	 * @return
	 */
	@RequestMapping(value = { "/buyersUsersList" })
	public void buyersUsersList() {

	}

	/**
	 * 买手用户列表数据
	 * 
	 * @param
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "/getBuyersUsersList" })
	public Object getbBuyersUsersList(BuyersVo vo, HttpServletRequest request) {
		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		List<Buyersusers> data = buyersUsersService.list(params, page);
		return new DataTableReturn(page.getDraw(), page.getTotal(), page.getTotal(), data);
	}

	/**
	 * 买手账号状态修改
	 * 
	 * @param id
	 * @param accountStatus
	 * @return
	 */
	@RequestMapping(value = { "/editBuyerStatus" })
	@ResponseBody
	public Result<?> editBuyerStatus(@RequestParam String id, @RequestParam String accountStatus) {

		try {
			Buyersusers user = buyersUsersService.get(id);
			if ("1".equals(accountStatus.trim())) {
				user.setAccountStatus(0);
				buyersUsersService.save(user);
				return new Result<Object>(true, "解冻账户成功");
			} else {
				user.setAccountStatus(1);
				buyersUsersService.save(user);

				return new Result<Object>(true, "冻结账户成功");
			}

		} catch (Exception e) {
			LOG.error("更改用户状态异常");
			return new Result<Object>(false, "操作失败");
		}
	}

	/**
	 * 买手用户详情
	 * 
	 * @param id
	 * @param model
	 */
	@RequestMapping(value = { "/buyerUserDetail" })
	public void buyerUserDetail(@RequestParam String id, ModelMap model) {
		Buyersusers user = buyersUsersService.get(id);
		model.addAttribute("user", user);
		Map<String, String> param = new HashMap<>();
		param.put("buyersUserID", id);
		List<Map<String, Object>> bankList = buyerBankCardService.list(param);
		model.put("bankList", bankList);
		List<Map<String, Object>> bindAccounts = bindingPlatformAccountsService.list(param);
		model.put("bindAccounts", bindAccounts);
		
		List<Map<String, Object>> creditRating = bindingPlatformAccountsService.getCreditRating(param);
		model.put("creditRating", creditRating);
		
		List<String> addresses = new ArrayList<String>();
		for (Map<String,Object> m : bindAccounts) {
			String address = "";
			String a1 = regionalInformationCache.getAreaName((String)m.get("province"));
			if (StringUtils.isNotBlank(a1)) {
				address += a1;
			}
			String a2 = regionalInformationCache.getAreaName((String)m.get("city"));
			if (StringUtils.isNotBlank(a2)) {
				address += a2;
			}
			String a3 = regionalInformationCache.getAreaName((String)m.get("area"));
			if (StringUtils.isNotBlank(a3)) {
				address += a1;
			}
			address += m.get("shippingaddress");
			addresses.add(address);
		}
		model.addAttribute("addresses", addresses);
	}

	/**
	 * 删除买手银行卡
	 * 
	 * @param id
	 * @param status
	 * @return
	 */
	@RequestMapping(value = { "/deleteBuyersBankCard" })
	@ResponseBody
	public Result<?> deleteBuyersBankCard(@RequestParam String buyersUserId, @RequestParam int bankcardid) {
		try {
			BuyersbankcardId id = new BuyersbankcardId(buyersUserId, bankcardid);
			Buyersbankcard card = buyerBankCardService.get(id);
			buyerBankCardService.delete(card);
			return new Result<Object>(true, "删除买手银行卡成功");
		} catch (Exception e) {
			LOG.error("删除买手银行卡异常", e);
			return new Result<Object>(false, "删除买手银行卡失败");
		}
	}

	@RequestMapping(value = { "/updateBindingPlatformAccounts" })
	@ResponseBody
	public Result<?> updateBindingPlatformAccounts(@RequestParam String platformAccountId, @RequestParam int creditRatingNo) {
		try {
			Bindingplatformaccounts entity = this.bindingPlatformAccountsService.get(platformAccountId);
			entity.setCreditRatingNo(creditRatingNo);
			bindingPlatformAccountsService.save(entity);
			return new Result<Object>(true, "修改信誉等级成功");
		} catch (Exception e) {
			LOG.error("修改信誉等级成功异常", e);
			return new Result<Object>(false, "操作失败");
		}
	}
	
	/**
	 * 账号状态改变
	 * 
	 * @param buyersUserId
	 * @param bankcardid
	 * @return
	 */
	@RequestMapping(value = { "/editBindingPlatformAccounts" })
	@ResponseBody
	public Result<?> editBindingPlatformAccounts(@RequestParam String platformAccountId, @RequestParam char status) {
		try {
			Bindingplatformaccounts entity = this.bindingPlatformAccountsService.get(platformAccountId);
			if (entity != null) {
				if (status == '1') {
					entity.setApprovalStatus('2');
					bindingPlatformAccountsService.save(entity);
					return new Result<Object>(true, "解绑成功");
				} else {
					entity.setApprovalStatus('1');
					bindingPlatformAccountsService.save(entity);
					return new Result<Object>(true, "绑定成功");
				}

			}
			return new Result<Object>(false, "操作失败");
		} catch (Exception e) {
			LOG.error("修改买手绑定账号异常", e);
			return new Result<Object>(false, "操作失败");
		}
	}

	/**
	 * 更新买手用户信息
	 * 
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = { "/updateBuyersUser" })
	@ResponseBody
	public Result<?> updateBuyersUser(BuyersVo vo) {

		try {
			Buyersusers buyer = this.buyersUsersService.get(vo.getBuyersUserID());
			System.err.println(buyer);
			if (buyer != null) {
				buyer.setUserName(vo.getUserName());
				if (!StringUtils.equals("notchange", vo.getLoginPassword())) {
					buyer.setLoginPassword(MD5UtilBuyer.MD5(vo.getLoginPassword()));
				}
				buyer.setPhone(vo.getPhone());
				buyer.setQqno(vo.getQqNo());
				buyer.setWechatNo(vo.getWechatNo());
				buyer.setFullName(vo.getFullName());
				buyer.setSex(vo.getSex());
				buyer.setIdcard(vo.getIdCard());
				buyer.setHeadPortrait(vo.getHeadPortrait());
				buyer.setIdcardphoto1(vo.getIdcardphoto1());
				buyer.setIdcardphoto2(vo.getIdcardphoto2());
				Buyersusers u = this.buyersUsersService.getByUserName(buyer.getUserName());

				if (u != null && !u.getBuyersUserId().equals(buyer.getBuyersUserId())) {
					// username已存在
					return new Result<Object>(false, "登录账号已存在");
				}
				buyersUsersService.save(buyer);
				return new Result<Object>(true, "用户信息更新成功");
			} else {
				return new Result<Object>(false, "查找的用户不存在,id:" + vo.getBuyersUserID());
			}
		} catch (Exception e) {
			LOG.error("更新用户异常", e);
			return new Result<Object>(false, "操作失败");
		}
	}

	@RequestMapping(value = { "/reportBuyers" })
	public ModelAndView reportBuyers(BuyersVo vo, HttpServletRequest request, HttpServletResponse response) {

		PageBean page = PageUtil.parseRequest2PageBean(request);
		Map<String, String> params = null;
		try {
			params = BeanUtils.describe(vo);
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			params = new HashMap<String, String>();
		}
		try {
			page.setPageSize(0);
			List<Buyersusers> datas = this.buyersUsersService.list(params, page);
			PoiReportBuilder builder = new PoiReportBuilder();
			builder.appendHeader("生财ID", "登陆账号", "注册时间", "联系电话", "QQ", "微信", "买手姓名", "账户状态");
			if (datas != null) {
				for (Buyersusers data : datas) {
					List<String> poiData = new ArrayList<>();
					poiData.add(data.getBuyersUserId());
					poiData.add(data.getUserName());
					poiData.add(DateFormatUtils.format(data.getRegistrationTime(), CommonConstant.TIME_FORMAT_YMDHMS));
					poiData.add(data.getPhone());
					poiData.add(data.getQqno());
					poiData.add(data.getWechatNo());
					poiData.add(data.getFullName());
					poiData.add(data.getAccountStatus() == 0 ? "使用中" : "已冻结");
					builder.appendData(poiData.toArray(new String[poiData.size()]));
				}
			}

			response.reset();// 不加这一句的话会出现下载错误
			String fileName = "买手账户_" + System.currentTimeMillis() + ".xls";
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1")); // 设定输出文件头
			response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 定义输出类型
			builder.write(response.getOutputStream());
			return null;
		} catch (Exception e) {
			LOG.error("导出买手账户异常", e);
			request.setAttribute("message", e.getMessage());
			return new ModelAndView("error.jsp");
		}
	}
}
